package com.gash.scrape;

import java.io.FileReader;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileParser {

	public static void main(String[] args) throws Exception{
		List<ParseObject> objs = parse(args[0]);
		int count = 0;
		for (ParseObject o : objs) {
			count++;
			System.out.println(count + ". Title: " + o.title);
			System.out.println("   URL: " + o.url);
		}
		
		System.out.println("Found: " + count);
	}

	public static List<ParseObject> parse(String filename) throws Exception {
		BufferedReader input = new BufferedReader(new FileReader(filename));
		List<ParseObject> objs = new ArrayList<ParseObject>();
		
		while (true) {
			ParseObject page = parseOne(input);
			
			if (page == null)
				break;
			
			objs.add(page);
		}
		
		input.close();
		return objs;
	}

	private static ParseObject parseOne(BufferedReader input) throws Exception {
		String line = null;
		ParseObject page = new ParseObject();
		
		line = input.readLine();
		if (line == null)
			return null;
		
		page.title = line.substring(7);
		page.url   = input.readLine().substring(5);
		
		line = input.readLine();
		if (line.matches("Keywords: .+")) {
			page.keywords = new ArrayList<String>(Arrays.asList(line.substring(10).split(",")));
		}
		
		line = input.readLine();
		if (line.startsWith("Links:")) {
			while ((line = input.readLine()) != null) {
				if (line.equals("")) {
					break;
				}
				page.links.add(line);
			}
		}
		
		line = input.readLine();
		if (line.startsWith("Citations:")) {
			while ((line = input.readLine()) != null) {
				if (line.equals(""))
					break;
				page.citations.add(line);
			}
		}
		
		return page;
	}
}